package com.linkage.jz.bankruptcy.activity.Project.ZQUser.DetailOper;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Main.CreateAddrActivity;
import com.linkage.jz.bankruptcy.activity.Project.CreateProPublicActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.AddProxyUserActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ChangeZQUserBaseInfoActivity;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.MyAddr;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailBaseInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.activity.project.DissentActionActivity;
import com.linkage.seapeak.pojo.UploadImage;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 *
 * 变更债权人名称
 */
public class ChangerZQUserNameActivity extends BaseCreateActivity implements OnClickListener {
    private static final String TAG = ChangerZQUserNameActivity.class.getSimpleName();



    @Override
    public void setListener() {

    }

    @Override
    public void initTitle() {
    }

    @Override
    public void initView() {

    }
    private EditText et_Name,et_socialcode,et_fddbz,et_openbank,et_countname,et_fddbrzfzm,et_chanegenote;
    private RecyclerView mImgRecyclerView;
    private TextView textSum;
    private Button titlebar_back;

    private List<UploadImage> mImgList = new ArrayList<>();
    private GridImagesAdapter mImgAdapter;
    private RadioGroup radioGroupNumber;

//    CommonPromptDialog mPromptDialog;
    private static ZQUserDetailBaseInfo mInfo;

    private static String mType;
    private static int mUserType;//0管理人 1 债权人

    public static void start(Context context, ZQUserDetailBaseInfo info, String type, int userType) {
        Intent intent = new Intent(context, ChangerZQUserNameActivity.class);
        mInfo = info;
        mType = type;
        mUserType = userType;
        context.startActivity(intent);
    }


    private CommonPromptDialog mPromptDialog;
    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        mPromptDialog = new CommonPromptDialog(this,CommonPromptDialog.TYPE_TIPS);
        mPromptDialog.setContent("放弃编辑？");
        mPromptDialog.setPositiveClickListener("是", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChangerZQUserNameActivity.super.onBackPressed();
            }
        });
        mPromptDialog.setNegativeClickListener("否", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPromptDialog.dismiss();
            }
        });
        mPromptDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_edit_zq_rename_user);
        super.onCreate(savedInstanceState);
        titlebar_title = findViewById(R.id.top_title);
        titlebar_title.setText("变更债权人名称");
        titlebar_back = findViewById(R.id.top_back1);

        radioGroupNumber = (RadioGroup) findViewById(R.id.radio_group_number);
        titlebar_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        ((RadioGroup) findViewById(R.id.radio_group_number)).setOnCheckedChangeListener((radioGroup, which) -> {
            if (which == R.id.number_left) {
//                provideBusinessLicense = TYPE_UPLOAD;
                findViewById(R.id.recycler_imgs).setVisibility(View.VISIBLE);
            } else if (which == R.id.number_right) {
//                provideBusinessLicense = TYPE_LOCAL;
                findViewById(R.id.recycler_imgs).setVisibility(View.GONE);
            }
        });


        initViews();
        initData();


    }



    private void initViews() {
        titlebar_back = findViewById(R.id.top_back1);

        titlebar_menu_text = findViewById(R.id.top_mune1);
        titlebar_back.setOnClickListener(this);
        titlebar_menu_text.setText("提交");
        titlebar_menu_text.setVisibility(View.VISIBLE);

        titlebar_menu_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
            }
        });

        et_Name = findViewById(R.id.et_Name);
        et_socialcode = findViewById(R.id.et_socialcode);
        et_fddbz = findViewById(R.id.et_fddbz);
        et_countname = findViewById(R.id.et_countname);
        et_fddbrzfzm = findViewById(R.id.et_fddbrzfzm);
        et_chanegenote = findViewById(R.id.et_chanegenote);
        et_openbank = findViewById(R.id.et_openbank);

        textSum = findViewById(R.id.textSum);

        et_chanegenote.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String tempStr = et_chanegenote.getText().toString();
                if (tempStr.length() < 300) {
                    textSum.setText(tempStr.length() + "/300");
                } else {
                    et_chanegenote.setText(tempStr.substring(0, 300));
                    textSum.setText("300/300");
                }
            }
        });
        if(mInfo !=null)
        {
            et_Name.setText(mInfo.getCreditorName());
            et_socialcode.setText(mInfo.getSocialUniformCreditCode());
            et_fddbz.setText(mInfo.getLegalRepresentativeName());
        }

        mImgRecyclerView = findViewById(R.id.recycler_imgs);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mImgRecyclerView.setLayoutManager(manager);
        mImgAdapter = new GridImagesAdapter(this, TYPE_EDIT);
        mImgAdapter.setList(mImgList);
        mImgRecyclerView.setAdapter(mImgAdapter);


    }

    @Override
    public void initData() {


    }

    private boolean showflag = true;

//    @Override
//    public void onBackPressed() {
////        super.onBackPressed();
////        findViewById(R.id.titlebar_back).performClick();
////        findViewById(R.id.titlebar_back).performClick();
//        noticeDialog = new PublicNoticeDialog(ChangerZQUserNameActivity.this, new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (v.getId() == R.id.btn_save_notice) {
//                    finish();
//                    noticeDialog.dismiss();
//                } else {
//                    noticeDialog.dismiss();
//                }
//            }
//        }, 1, "提示", "放弃编辑？",
//                "否", "是");
//        noticeDialog.show();
//    }


    private PublicNoticeDialog noticeDialog;
    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {

            case R.id.titlebar_menu_text:
                saveData();
                break;
            case R.id.top_back1:
                noticeDialog = new PublicNoticeDialog(ChangerZQUserNameActivity.this, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (v.getId() == R.id.btn_save_notice) {
                            finish();
                            noticeDialog.dismiss();
                        } else {
                            noticeDialog.dismiss();
                        }
                    }
                }, 1, "提示", "放弃编辑？",
                        "否", "是");
                noticeDialog.show();
                break;
            default:
                break;
        }
    }

    public void saveData() {

        String str_et_Name = et_Name.getText().toString();
        if (TextUtils.isEmpty(str_et_Name)) {
//            ToastUtil.showShort("申报债权人名称不能为空");
            showToast("申报债权人名称不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }
        String str_et_socialcode = et_socialcode.getText().toString();
        if (TextUtils.isEmpty(str_et_socialcode) ) {
//            ToastUtil.showShort("统一社会信用代码证不能为空");
            showToast("统一社会信用代码证不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        String str_et_fddbz = et_fddbz.getText().toString();
        if (TextUtils.isEmpty(str_et_fddbz) ) {
//            ToastUtil.showShort("法定代表人不能为空");
            showToast("法定代表人不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
            return;
        }

        String str_et_chanegenote = et_chanegenote.getText().toString();
//        if (TextUtils.isEmpty(str_et_chanegenote) ) {
//            ToastUtil.showShort("变更说明不能为空");
//            return;
//        }

//        if(mImgList.size()<1)
//        {
//            ToastUtil.showShort("证明文件不能为空");
//            return;
//        }
        int num = 0;
        for (UploadImage image : mImgList) {
            if (TextUtils.equals(image.getFilename(), NAME_ADD)) {
                continue;
            }
            num ++;
        }

        if (num == 0 &&  radioGroupNumber.getCheckedRadioButtonId() == R.id.number_left) {
            showToast("证明文件不能为空", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
//            showToast("证明文件不能为空");
            return;
        }

//        JSONArray fileArr = new JSONArray();
//        for (int i = 0; i < mImgList.size(); i++) {
//            fileArr.put(mImgList.get(i).parse2JSON());
//        }
        JSONArray fileArr = new JSONArray();
        for (int i = 0; i < mImgList.size(); i++) {
            if (TextUtils.equals(mImgList.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                obj.putOpt("attachmentName", "相关附件"+(i+1)+".jpg");
                obj.putOpt("attachmentDownloadAddress", mImgList.get(i).getFilepath());
                obj.putOpt("attachmentSize", mImgList.get(i).getFilesize());
                obj.putOpt("loadUrl", mImgList.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


        mShapeLoadingDialog.setLoadingText("提交信息中...");
        mShapeLoadingDialog.setCanceledOnTouchOutside(false);
        mShapeLoadingDialog.show();
        Observable<JsonObject> observable;


        Map<String, String> parms = new HashMap<>();
        parms.put("userToken", getUserToken());
        parms.put("projectId", mInfo.getBankruptcyProjectId());
        parms.put("creditorId", mInfo.getId() + "");
        parms.put("creditorName", str_et_Name);
        parms.put("socialUniformCreditCode", str_et_socialcode);
        parms.put("legalRepresentativeName", str_et_fddbz);
        parms.put("bank", et_openbank.getText().toString());
        parms.put("bankBranch", "");

        parms.put("bankAccountName", et_countname.getText().toString());
        parms.put("bankAccount", et_fddbrzfzm.getText().toString());
        parms.put("changeDetail", str_et_chanegenote + "");
        parms.put("proveFileJson", fileArr.toString());
        parms.put("type", mUserType + "");


        Network.getAPIService()
                .changeCreditorInfoNameMore(parms)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        mShapeLoadingDialog.dismiss();
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onNext(json);
                            return;
                        }
                        RefreshEvent event = new RefreshEvent();
                        event.setType(RefreshEvent.TYPE_TALK);
                        EventBus.getDefault().post(event);

                        if(mUserType== 1)
                        {
                            noticeDialog = new PublicNoticeDialog(ChangerZQUserNameActivity.this, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (v.getId() == R.id.btn_save_notice) {
                                    }
                                    noticeDialog.dismiss();
                                    finish();
                                }
                            }, 5, "提示", "变更债权人名称信息已经提交管理人审核，如有疑问，可于管理人联系。",
                                    "取消", "确认");
                            noticeDialog.show();
//                            finish();

                        }else {
//                            ToastUtil.showShort("提交成功");
                            showToast("提交成功", com.linkage.seapeak.utils.ToastUtil.TOAST_TYPE.WARNING);
                            finish();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mShapeLoadingDialog.dismiss();
                        super.onError(e);
                    }
                });
    }


}

